//
//  Database.m
//  Hairdressing
//
//  Created by jiangtao on 13-11-2.
//  Copyright (c) 2013年 jiangtao. All rights reserved.
//

#import "DBAccess.h"
#import "FMDatabase.h"

@interface DBAccess ()

@end
@implementation DBAccess

static DBAccess * _sharedDBManager;

+ (DBAccess *) defaultDBManager {
	if (!_sharedDBManager) {
		_sharedDBManager = [[DBAccess alloc] init];
	}
	return _sharedDBManager;
}

- (id) init {
    self = [super init];
    if (self) {
        BOOL state = [self initDatabase];
        if (!state) {
            NSLog(@"数据库初始化失败");
        } else {
            NSLog(@"数据库初始化成功");
        }
    }
    return self;
}



- (BOOL)initDatabase
{
	BOOL success;
	NSError *error;
	NSFileManager *fm = [NSFileManager defaultManager];
	NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:DATABASE_NAME];
	NSLog(@"%@",writableDBPath);
	success = [fm fileExistsAtPath:writableDBPath];
	
	if(!success){
		NSString *defaultDBPath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:DATABASE_NAME];
		NSLog(@"%@",defaultDBPath);
		success = [fm copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
		if(!success){
			NSLog(@"error: %@", [error localizedDescription]);
		}
		success = YES;
	}
	
	if(success){
        if (!_dataBase) {
            _dataBase = [[FMDatabase alloc]initWithPath:writableDBPath];
        }
		if ([_dataBase open]) {
			[_dataBase setShouldCacheStatements:YES];
		}else{
			NSLog(@"Failed to open database.");
			success = NO;
		}
	}
	
	return success;
}


- (void)closeDatabase
{
	[_dataBase close];
    _sharedDBManager = nil;
}


- (void)dealloc
{
	[self closeDatabase];
    [super dealloc];
}

@end
